<template>
  <n-card :bordered="false">
    <n-alert :show-icon="false" class="m-b-10">
      <n-form :model="search_param" class="search-forms"
              :show-feedback="false"
              label-placement="left"
              :label-width="50"
              @keydown.enter.prevent="handleSubmitSearch">
        <n-form-item label="性别:">
          <n-space>
            <n-button size="small" :type="search_param.gender==null?'primary':'default'"
                      @click="handelSelectSearchOption(null,'gender')">全部
            </n-button>
            <template v-for="item in genderOption">
              <n-button size="small" :type="search_param.gender==item.value?'primary':'default'"
                        @click="handelSelectSearchOption(item.value,'gender')">{{ item.label }}
              </n-button>
            </template>
          </n-space>
        </n-form-item>
        <n-form-item label="认证:">
          <n-space>
            <n-button size="small" :type="search_param.auth==null?'primary':'default'"
                      @click="handelSelectSearchOption(null,'auth')">全部
            </n-button>
            <template v-for="item in authOption">
              <n-button size="small" :type="search_param.auth==item.value?'primary':'default'"
                        @click="handelSelectSearchOption(item.value,'auth')">{{ item.label }}
              </n-button>
            </template>
          </n-space>
        </n-form-item>
        <n-form-item label="状态:">
          <n-space>
            <n-button size="small" :type="search_param.status==null?'primary':'default'"
                      @click="handelSelectSearchOption(null,'status')">全部
            </n-button>
            <template v-for="item in statusOption">
              <n-button size="small" :type="search_param.status==item.value?'primary':'default'"
                        @click="handelSelectSearchOption(item.value,'status')">{{ item.label }}
              </n-button>
            </template>
          </n-space>
        </n-form-item>
        <n-form-item label="忙碌:">
          <n-space>
            <n-button size="small" :type="search_param.beBusy==null?'primary':'default'"
                      @click="handelSelectSearchOption(null,'beBusy')">全部
            </n-button>
            <template v-for="item in busyOption">
              <n-button size="small" :type="search_param.beBusy==item.value?'primary':'default'"
                        @click="handelSelectSearchOption(item.value,'beBusy')">{{ item.label }}
              </n-button>
            </template>
          </n-space>
        </n-form-item>
        <n-form-item label="电话:">
          <n-space>
            <n-input v-model:value="search_param.phone" maxlength="11" placeholder="电话号码" clearable/>
          </n-space>
        </n-form-item>
        <n-form-item label="&nbsp;">
          <n-space>
            <n-input v-model:value="search_param.key" style="width: 320px"
                     placeholder="请输入姓名、身份证号码或毕业院校查询"
                     clearable/>
            <search-button-group @submit="handleSubmitSearch"
                                 @reset="handleResetSearch"/>
          </n-space>
        </n-form-item>
      </n-form>
    </n-alert>
    <data-table ref="data_list"
                :columns="columns"
                :action-column="actionColumn"
                :row-key="(row:Recordable) => row.id"
                :params="search_param"
                list-url="teacher/list">
      <template #toolbarLeft>
        <n-button type="success" v-permission="['teacher:add']" @click="()=>(addEditModel=true)">
          <n-icon :size="18">
            <AddSharp/>
          </n-icon>
          新增
        </n-button>
      </template>
    </data-table>
  </n-card>
  <!--新增、修改-->
  <n-modal v-model:show="addEditModel"
           :title="addEditForm.id?'修改教师':'新增教师'" :mask-closable="false"
           :show-icon="false" preset="dialog" style="width: 1180px" @after-leave="closeAddEditModel">
    <n-form ref="addEditFormRef" :model="addEditForm" :rules="addEditFormRules" require-mark-placement="left"
            label-placement="left" :label-width="80">
      <n-tabs type="line" animated tab-style="font-weight: 500;">
        <n-tab-pane name="oasis" tab="基础信息">
          <div style="height: 700px;overflow: auto">
            <n-grid :x-gap="12" :y-gap="12" :cols="7" layout-shift-disabled>
              <n-gi :span="6">
                <n-grid :cols="24" :x-gap="24">
                  <n-form-item-gi :span="7" label="姓名" path="name">
                    <n-input v-model:value="addEditForm.name" placeholder="请填写教师姓名" clearable/>
                  </n-form-item-gi>
                  <n-form-item-gi :span="10" label="身份证号" path="idCard">
                    <n-input v-model:value="addEditForm.idCard" maxlength="18" placeholder="请填写教师身份证号"
                             clearable/>
                  </n-form-item-gi>
                  <n-form-item-gi :span="7" label="出生日" path="birthday">
                    <n-date-picker v-model:value="birthdayDate" type="date" @update:value="selectedBirthday"
                                   placeholder="出生日期" clearable/>
                  </n-form-item-gi>
                </n-grid>
              </n-gi>
              <n-gi style="position: relative;">
                <div style="position: absolute;padding: 6px 0">
                  <n-form-item label="&nbsp;" path="avatar" :label-width="30">
                    <image-selection v-model:value="addEditForm.avatar" :width="90" :height="90"/>
                  </n-form-item>
                </div>
              </n-gi>
            </n-grid>
            <n-grid :x-gap="12" :y-gap="12" :cols="7" layout-shift-disabled>
              <n-gi :span="6">
                <n-grid :cols="24" :x-gap="24">
                  <n-form-item-gi :span="7" label="手机号码" path="phone">
                    <n-input v-model:value="addEditForm.phone" maxlength="11" placeholder="请填写教师手机号码"
                             clearable/>
                  </n-form-item-gi>
                  <n-form-item-gi :span="10" label="绑定用户" path="userId">
                    <n-select v-model:value="addEditForm.userId" :options="usersOptions" :render-label="renderUserLabel"
                              :render-tag="renderSingleSelectTag" filterable placeholder="请选择用户" clearable/>
                  </n-form-item-gi>
                  <n-form-item-gi :span="7" label="性别" path="gender">
                    <n-radio-group v-model:value="addEditForm.gender" name="gender">
                      <n-space>
                        <n-radio v-for="sex in genderOption" :key="sex.value" :value="sex.value">
                          {{ sex.label }}
                        </n-radio>
                      </n-space>
                    </n-radio-group>
                  </n-form-item-gi>
                </n-grid>
              </n-gi>
            </n-grid>
            <n-grid :x-gap="12" :y-gap="12" :cols="7" layout-shift-disabled>
              <n-gi :span="6">
                <n-grid :cols="24" :x-gap="24">
                  <n-form-item-gi :span="16" label="籍贯" path="county">
                    <n-space>
                      <n-select v-model:value="addEditForm.province" :options="provinceOption"
                                @update:value="getCityOption($event,0)" style="width: 190px" clearable/>
                      <n-select v-model:value="addEditForm.city" :options="cityOptions"
                                @update:value="getCountyOption($event,0)"
                                style="width: 170px" clearable/>
                      <n-select v-model:value="addEditForm.county" :options="countyOptions" style="width: 160px"
                                clearable/>
                    </n-space>
                  </n-form-item-gi>
                  <n-form-item-gi :span="8" label="详细地址" path="address">
                    <n-input v-model:value="addEditForm.address" placeholder="请填写详细地址" clearable/>
                  </n-form-item-gi>
                </n-grid>
              </n-gi>
            </n-grid>
            <n-grid :cols="24" :x-gap="24">
              <n-form-item-gi :span="6" label="辅导方式" path="tutor">
                <n-select v-model:value="addEditForm.tutor" :options="tutorOption" placeholder="请选择辅导方式"
                          clearable/>
              </n-form-item-gi>
              <n-form-item-gi :span="9" label="毕业院校" path="graduate">
                <n-input v-model:value="addEditForm.graduate" placeholder="请填写教师毕业院校" clearable/>
              </n-form-item-gi>
              <n-form-item-gi :span="9" label="所学专业" path="major">
                <n-input v-model:value="addEditForm.major" placeholder="请填写教师所学专业" clearable/>
              </n-form-item-gi>
            </n-grid>
            <n-grid :cols="24" :x-gap="24">
              <n-form-item-gi :span="6" label="学历" path="education">
                <n-select v-model:value="addEditForm.education" :options="educationOption" placeholder="请选择学历"
                          clearable/>
              </n-form-item-gi>
              <n-form-item-gi :span="18" label="授课区域" path="tArea">
                <n-cascader v-model:value="addEditForm.tArea" :options="TeachingAreaOptions" multiple check-strategy="child"
                            clearable/>
              </n-form-item-gi>
            </n-grid>
            <n-grid :cols="24" :x-gap="24">
              <n-form-item-gi :span="6" label="目前身份" path="currentIdentity">
                <n-input v-model:value="addEditForm.currentIdentity" placeholder="请填写教师目前身份" clearable/>
              </n-form-item-gi>
              <n-form-item-gi :span="18" label="工作地" path="wCounty">
                <n-space>
                  <n-select v-model:value="addEditForm.wProvince" :options="provinceOption"
                            @update:value="getCityOption($event,1)" style="width: 260px" clearable/>
                  <n-select v-model:value="addEditForm.wCity" :options="wCityOptions"
                            @update:value="getCountyOption($event,1)" style="width: 240px" clearable/>
                  <n-select v-model:value="addEditForm.wCounty" :options="wCountyOptions" style="width: 230px"
                            clearable/>
                </n-space>
              </n-form-item-gi>
            </n-grid>
            <n-grid :cols="24" :x-gap="24">
              <n-form-item-gi :span="6" label="微信号" path="wechat">
                <n-input v-model:value="addEditForm.wechat" placeholder="请填写微信号" clearable/>
              </n-form-item-gi>
              <n-form-item-gi :span="11" label="预约设定" path="res">
                <div class="m-t-5">
                  <n-radio-group v-model:value="addEditForm.res" name="radiogroup">
                    <n-space>
                      <n-radio :value="0" label="每天"/>
                      <n-radio :value="1" label="指定星期"/>
                      <n-radio :value="2" label="指定日期"/>
                    </n-space>
                  </n-radio-group>
                  <p class="tips_p">指定星期(如：星期一，星期二)、指定日期(如：20日)</p>
                </div>
              </n-form-item-gi>
              <n-form-item-gi :span="7" label="预约日期" path="day">
                <template v-if="addEditForm.res===0 || addEditForm.res===1">
                  <n-select v-model:value="addEditForm.day" multiple :disabled="addEditForm.res===0"
                            :options="weekOptions"
                            clearable/>
                </template>
                <template v-if="addEditForm.res===2">
                  <n-date-picker v-model:value="addEditForm.resDay" type="date" @update:value="changeResDay"
                                 placeholder="预约日期" clearable/>
                </template>
              </n-form-item-gi>
            </n-grid>
            <n-grid :cols="24" :x-gap="24">
              <n-form-item-gi :span="6" label="预约时间" path="allDay">
                <div class="m-t-5">
                  <n-radio-group v-model:value="addEditForm.allDay" name="allDayRadioGroup">
                    <n-space>
                      <n-radio :value="0" label="时间段"/>
                      <n-radio :value="1" label="全天"/>
                    </n-space>
                  </n-radio-group>
                  <p class="tips_p">选择时间段时必须填写时间段</p>
                </div>
              </n-form-item-gi>
              <n-form-item-gi :span="8" label="上午时间" path="morningAppTime">
                <n-time-picker v-model:value="addEditForm.morningAppTimeStart" @update:value="morningAppTimeStartValue"
                               :disabled="addEditForm.allDay===1"
                               format="h:mm a" clearable/>
                &nbsp;-&nbsp;
                <n-time-picker v-model:value="addEditForm.morningAppTimeEnd" @update:value="morningAppTimeEndValue"
                               :disabled="addEditForm.allDay===1"
                               format="h:mm a" clearable/>
              </n-form-item-gi>
              <n-form-item-gi :span="8" label="下午时间" path="afternoonAppTime">
                <n-time-picker v-model:value="addEditForm.afternoonAppTimeStart"
                               @update:value="afternoonAppTimeStartValue" :disabled="addEditForm.allDay===1"
                               format="h:mm a" clearable/>
                &nbsp;-&nbsp;
                <n-time-picker v-model:value="addEditForm.afternoonAppTimeEnd" @update:value="afternoonAppTimeEndValue"
                               :disabled="addEditForm.allDay===1"
                               format="h:mm a" clearable/>
              </n-form-item-gi>
            </n-grid>
            <n-grid :cols="24" :x-gap="24">
              <n-form-item-gi :span="24" label="教授科目" path="tCourse">
                <n-select v-model:value="addEditForm.tCourse" :options="courseOptions" :render-label="renderLabelSuffix"
                          label-field="name"
                          value-field="id"
                          filterable multiple placeholder="请选择教授科目" clearable/>
              </n-form-item-gi>
            </n-grid>
            <n-grid :cols="24" :x-gap="24">
              <n-form-item-gi :span="24" label="自我评价" path="evaluation">
                <n-input v-model:value="addEditForm.evaluation"
                         placeholder="自我评价"
                         type="textarea"
                         size="small"
                         :autosize="{minRows: 3,maxRows: 5}"
                />
              </n-form-item-gi>
            </n-grid>
            <n-grid :cols="24" :x-gap="24">
              <n-form-item-gi :span="6" label="课时价目" path="cPrice" >
                  <n-input-group>
                    <n-input-number v-model:value="addEditForm.cPrice" :precision="2" :show-button="false" clearable/>
                    <n-input-group-label>/小时</n-input-group-label>
                  </n-input-group>
              </n-form-item-gi>
              <n-form-item-gi :span="4" label="状态" path="status" >
                <n-switch :round="false" v-model:value="addEditForm.status" :checked-value="1" :unchecked-value="0">
                  <template #checked>
                    正常
                  </template>
                  <template #unchecked>
                    停职
                  </template>
                </n-switch>
              </n-form-item-gi>
              <n-form-item-gi :span="4" label="是否推荐" path="isRec">
                <n-switch :round="false" v-model:value="addEditForm.isRec" :checked-value="1" :unchecked-value="0">
                  <template #checked>
                    是
                  </template>
                  <template #unchecked>
                    否
                  </template>
                </n-switch>
              </n-form-item-gi>
              <n-form-item-gi :span="6" label="是否忙碌" path="beBusy" >
                <n-radio-group v-model:value="addEditForm.beBusy" name="beBusy">
                  <n-radio :value="1" label="是"/>
                  <n-radio :value="0" label="否"/>
                </n-radio-group>
              </n-form-item-gi>
              <n-form-item-gi :span="4" label="认证状态" path="auth" >
                <n-switch :round="false" v-model:value="addEditForm.auth" :checked-value="1" :unchecked-value="0">
                  <template #checked>
                    认证
                  </template>
                  <template #unchecked>
                    未认证
                  </template>
                </n-switch>
              </n-form-item-gi>
            </n-grid>
          </div>
        </n-tab-pane>
        <n-tab-pane name="the beatles" tab="证件资料">
          <div style="height: 540px">
            <n-form-item label="身份证图片" path="idCardPhoto" :label-width="90">
              <image-selection v-model:value="addEditForm.idCardPhoto"/>
            </n-form-item>
            <n-form-item label="在职证明" path="jobProve" :label-width="90">
              <image-selection v-model:value="addEditForm.jobProve"/>
            </n-form-item>
            <n-form-item label="毕业证书" path="diploma" :label-width="90">
              <image-selection v-model:value="addEditForm.diploma"/>
            </n-form-item>
            <n-grid :cols="24" :x-gap="24">
              <n-form-item-gi :span="24" label="荣誉证书" path="honor" :label-width="90">
                <image-selection v-model:value="addEditForm.honor" :count="8" :cols="8" :gap="16"/>
              </n-form-item-gi>
            </n-grid>
            <n-grid :cols="24" :x-gap="24">
              <n-form-item-gi :span="24" label="其他证书" path="certificate" :label-width="90">
                <image-selection v-model:value="addEditForm.certificate" :count="4" :cols="4" :gap="16"/>
              </n-form-item-gi>
            </n-grid>
          </div>
        </n-tab-pane>
      </n-tabs>
    </n-form>
    <template #action>
      <n-space>
        <n-button @click="()=>(addEditModel=false)">取消</n-button>
        <n-button type="primary" :loading="handelSubmitLoading" @click="handelSubmitData">确定
        </n-button>
      </n-space>
    </template>
  </n-modal>
</template>
<script setup lang="ts">
import {computed, h, reactive, ref, watch, onBeforeMount} from 'vue';
import SearchButtonGroup from '@components/SearchButtonGroup';
import {
  FormInst,
  FormItemRule,
  NIcon,
  NImage,
  NPopconfirm,
  NTag,
  SelectOption,
  useMessage,
  CascaderOption,
  TreeSelectOption,
  NAvatar,
  NText, NSwitch, NEllipsis
} from 'naive-ui';
import DataTable from '@components/DataTable';
import DataTableAction from '@components/DataTable/src/components/DataTableAction';
import {Config} from '@/config';

import {AddSharp, BeenhereRound} from '@vicons/material'
import {delRequest, getRequest, postPutRequest} from '@/api/data.ts';
import DateFns from '@/util/dateFns.ts';
import {extractInfoFromIDCard} from '@/util'


import ImageSelection from "@components/ImageSelection";
import {imagePreview} from '@/util';

const message = useMessage()

//学历
const educationOption = ref<SelectOption[]>([
  {
    label: '初中',
    value: 1
  }, {
    label: '高中',
    value: 2
  }, {
    label: '大专',
    value: 3
  }, {
    label: '本科',
    value: 4
  }, {
    label: '硕士研究生',
    value: 5
  }, {
    label: '博士研究生',
    value: 6
  }
])

const genderOption = ref<SelectOption[]>([
  {
    label: '男',
    value: 1,
  }, {
    label: '女',
    value: 2,
  }
])
const statusOption = ref<SelectOption[]>([
  {
    label: '正常',
    value: 1,
  }, {
    label: '停职',
    value: 0,
  }
])
const authOption = ref<SelectOption[]>([
  {
    label: '未认证',
    value: 0,
  }, {
    label: '已认证',
    value: 1,
  }
])
const busyOption = ref<SelectOption[]>([
  {
    label: '空闲',
    value: 0,
  }, {
    label: '忙碌',
    value: 1,
  }
])
const tutorOption = ref<SelectOption[]>([
  {
    label: '本人上门',
    value: 1,
  }, {
    label: '网上辅导',
    value: 2,
  }, {
    label: '本人上门、网上辅导',
    value: 3,
  }
])
const reginData = ref<CascaderOption[]>([])
const weekOptions = ref<SelectOption[]>([
  {
    label: "星期一",
    value: 1,
  }, {
    label: "星期二",
    value: 2,
  }, {
    label: "星期三",
    value: 3,
  }, {
    label: "星期四",
    value: 4,
  }, {
    label: "星期五",
    value: 5,
  }, {
    label: "星期六",
    value: 6,
  }, {
    label: "星期日",
    value: 7,
  }
])
const usersOptions = ref<SelectOption[]>([]);
const courseOptions = ref<any[]>([]);
//查询条件
const search_param = ref({
  key: null,
  phone: null,
  gender: null,
  auth: null,
  beBusy: null,
  status: <number | string | null | undefined>null,
})

//数据表
const data_list = ref<any>();
const columns = ref([
  {
    title: 'ID',
    key: 'id',
    width: 60,
    align: 'center',
  }, {
    title: '头像',
    key: 'avatar',
    width: 60,
    render(row: { avatar: string }) {
      if (row.avatar) {
        return h(NAvatar, {
          size:30,
          src: imagePreview(row.avatar)
        })
      }
    }
  },
  {
    title: '姓名',
    key: 'name',
  }, {
    title: '身份证号码',
    key: 'idCard',
    width: 180,
  }, {
    title: '电话',
    key: 'phone',
    width: 115,
  }, {
    title: '性别',
    key: 'gender',
    width: 60,
    align: 'center',
    render(row: { gender: boolean | number }) {
      const genderText = row.gender == 1 ? '男' : '女';
      return h('span', null, {default: () => (genderText)})
    }
  }, {
    title: '出生日期',
    key: 'birthday',
    width: 100,
    align: 'center',
  },
  // {
  //   title: '余额(元)',
  //   key: 'money',
  //   width: 120,
  //   align: 'center',
  //   render(row: { money: number }) {
  //     return h('span', null, {default: () => (row.money.toFixed(2))})
  //   }
  // },

  {
    title: '学历',
    key: 'education',
    width: 100,
    align: 'center',
    render(row: { education: number }) {
      return h('span', null, {default: () => (getEdu(row.education))})
    }
  }, {
    title: '毕业院校',
    key: 'graduate'
  }, {
    title: '用户微信',
    key: 'user',
    width: 120,
    render(row: { user: { nickname: string, avatar: string } }) {
      return h('div', {style: {width: '100%', display: 'flex'}}, {
        default: () => (
            [
              h(NImage, {width: 30, height: 30, src: imagePreview(row.user.avatar)}),
              h(NEllipsis, {style: {display: 'block', paddingLeft: '5px'}}, {default: () => (row.user.nickname)})
            ])
      })
    }
  }, {
    title: '是否忙碌',
    key: 'beBusy',
    width: 80,
    align: 'center',
    render(row: { beBusy: number }) {
      const enabled_color = row.beBusy ? '#d03050' : '#18a058';
      const enabled_text = row.beBusy ? '忙碌' : '空闲';
      return h('div', {
        style: {
          display: 'flex',
          alignItems: 'center',
        }
      }, {
        default: () => (
            [h('span', {
              style: {
                display: 'block',
                width: '8px',
                height: '8px',
                borderRadius: '10px',
                backgroundColor: enabled_color,
              }
            }),
              h('span', {
                style: {
                  display: 'block',
                  paddingLeft: '2px'
                }
              }, {default: () => (enabled_text)})
            ])
      })
    }
  }, {
    title: '认证状态',
    key: 'auth',
    width: 80,
    align: 'center',
    render(row: { auth: number }) {
      return h(NIcon, {
        color: row.auth ? '#18a058' : 'rgba(194, 194, 194, 1)',
        size: 22
      }, {default: () => h(BeenhereRound)})
    }
  },
  {
    title: '状态',
    key: 'status',
    width: 80,
    align: 'center',
    render(row: { status: boolean | number }) {
      const enabled_color = row.status ? 'success' : 'warning';
      const enabled_text = row.status ? '正常' : '停职';
      return h(NTag,
          {
            type: enabled_color,
          },
          {
            default: () => (enabled_text),
          }
      );
    }
  }, {
    title: '创建时间',
    key: 'createTime',
    width: 175,
  }
])
//操作列
const actionColumn = reactive({
  width: 120,
  title: "操作",
  key: "action",
  fixed: "right",
  render(record: Recordable) {
    return h(DataTableAction, {
      actions: [
        {
          label: '修改',
          onClick: handleEdit.bind(null, record),
          type: 'primary',
          permission: ['teacher:edit']
        },
        {
          label: '删除',
          type: 'error',
          popConfirm: NPopconfirm,
          onPositiveClick: handleDelete.bind(null, record),
          confirm: {
            text: '确定删除当前教师吗？',
          },
          permission: ['teacher:del']
        },
      ]
    });
  },
});

//新增、修改
interface addEditFormItem {
  id?: number,
  userId?: number | null,
  name?: string | null | any,
  phone?: string | null | any,
  wechat?: string | null | any,
  idCard?: string | null | any,
  gender?: number,
  birthday?: string | null,
  graduate?: string | null,
  education?: number | null,
  major?: string | null,
  currentIdentity?: string | null,
  auth?: number,
  tutor?: number | null,
  province?: number | null,
  city?: number | null,
  county?: number | null,
  address?: string,
  wProvince?: number | null,
  wCity?: number | null,
  wCounty?: number | null,
  res?: number,
  day?: number[] | string | null,
  resDay?: number | null,
  isRec?: number,
  avatar?: string | null,
  idCardPhoto?: string | null,
  diploma?: string | null,
  honor?: string[] | undefined,
  jobProve?: string | null,
  certificate?: string[] | undefined,
  score?: number | null,
  status?: number,
  beBusy?: number,
  money?: number | null,
  evaluation?: string | null,
  tArea?: number[] | null,
  tCourse?: number[] | null,
  allDay?: number,
  morningAppTime?: string | null,
  afternoonAppTime?: string | null,
  morningAppTimeStart?: number | null,
  morningAppTimeEnd?: number | null,
  afternoonAppTimeStart?: number | null,
  afternoonAppTimeEnd?: number | null,
  morningAppTimeStartString?: string | null,
  morningAppTimeEndString?: string | null,
  afternoonAppTimeStartString?: string | null,
  afternoonAppTimeEndString: string | null,
  cPrice: number | null,
}

const addEditModel = ref<boolean>(false);
const handelSubmitLoading = ref<boolean>(false);
const addEditFormRef = ref<FormInst | null>(null);
const birthdayDate = ref<number | null>(null);//出生日
const provinceOption = computed(() => {
  return reginData.value.map((item): CascaderOption => ({
    label: item.label,
    value: item.value
  }));
})
const cityOptions = ref<SelectOption[] | undefined>([]);
const countyOptions = ref<SelectOption[] | undefined>([]);
const wCityOptions = ref<SelectOption[] | undefined>([]);
const wCountyOptions = ref<SelectOption[] | undefined>([]);
const TeachingAreaOptions=ref<CascaderOption[]>([]);//授课区域
const addEditForm = ref<addEditFormItem>({
  id: 0,
  userId: null,//微信绑定用户
  name: null,//教师名称
  phone: null,//手机号码
  wechat: null,//微信号
  idCard: null,//身份证号码
  gender: 1,//性别
  birthday: null,//出生日期
  graduate: null,//毕业院校
  education: null,//学历
  major: null,//所学专业
  currentIdentity: null,//目前身份
  auth: 0,//认证状态
  tutor: null,//辅导方式
  province: null,//教师所在省份
  city: null,//教师所在城市
  county: null,//教师所在县(区)
  address: '',//详细地址
  wProvince: null,//工作地址
  wCity: null,//工作地址
  wCounty: null,//工作地址(区)
  res: 0, //预约日期
  day: null,//预约日期
  resDay: null,//预约日期
  isRec: 0,//是否推荐
  avatar: null,//教师头像
  idCardPhoto: null,//身份证反面图片(人像面)
  diploma: null,//毕业证书/学信网正面
  honor: [],//荣誉证书
  jobProve: null,//在职证明
  certificate: [],//其他证书
  score: null,//教师评分
  status: 1,//状态
  beBusy: 0,//是否忙碌
  money: null,//余额
  evaluation: null,//自我评价
  tArea: [],//授课区域
  tCourse: [],//教授科目
  allDay: 0,//预约时间  1：全天  0：时间段
  morningAppTime: null,//上午时间段
  afternoonAppTime: null,//下午时间段
  morningAppTimeStart: null,//上午时间段开始
  morningAppTimeEnd: null,//上午时间段结束
  afternoonAppTimeStart: null,//下午开始时间
  afternoonAppTimeEnd: null,//下午结束时间
  morningAppTimeStartString: null,
  morningAppTimeEndString: null,
  afternoonAppTimeStartString: null,
  afternoonAppTimeEndString: null,
  cPrice: null,//课时价目
})

const addEditFormRules = computed(() => {
  return {
    name: {
      required: true,
      trigger: ['blur', 'input'],
      message: '请填写教师姓名'
    },
    phone: {
      required: true,
      trigger: ['blur', 'input'],
      message: '请填写教师电话号码'
    },
    idCard: {
      required: true,
      trigger: ['blur', 'input'],
      // message: '请填写教师身份证号码',
      asyncValidator: (_rule: FormItemRule, value: string) => {
        return new Promise<void>((resolve, reject) => {
          const reg = /^[1-9]\d{5}(19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[Xx\d]$/;
          if (!value) {
            addEditForm.value.birthday = null
            reject(Error('请填写教师身份证号码'))
          } else if (!reg.test(value)) {
            reject(Error('请填写正确的教师身份证号码')) // reject with error message
          } else {
            const fromIDCard: { birthday: string, gender: string } = extractInfoFromIDCard(value);
            addEditForm.value.birthday = fromIDCard.birthday;
            const gender: any | undefined = genderOption.value.find(item => item.label == fromIDCard.gender);
            addEditForm.value.gender = gender && gender.value;
            resolve()
          }
        })
      }
    },
    birthday: {
      required: true,
      trigger: ['blur', 'change'],
      message: '请选择教师出生日期'
    },
    gender: {
      type: 'number',
      required: true,
      trigger: ['blur', 'change'],
      message: '请选择教师性别'
    },
    education: {
      type: 'number',
      required: true,
      trigger: ['blur', 'change'],
      message: '请选择学历'
    },
    county: {
      type: 'number',
      required: true,
      trigger: ['blur', 'change'],
      message: '请选择籍贯'
    },
    tArea: {
      type: 'array',
      required: true,
      trigger: ['blur', 'change'],
      message: '请选择授课区域',

    },
    tutor: {
      type: 'number',
      required: true,
      trigger: ['blur', 'change'],
      message: '请选择辅导方式'
    },
    day: {
      type: addEditForm.value.res === 1 ? 'array' : 'string',
      required: addEditForm.value.res !== 0,
      trigger: ['blur', 'change'],
      message: addEditForm.value.res === 1 ? '请选择星期' : '请选择指定日期'
    },
    userId: {
      type: 'number',
      required: true,
      trigger: ['blur', 'change'],
      message: '请选择绑定用户'
    },
    graduate: {
      required: true,
      trigger: ['blur', 'input'],
      message: '请填写毕业院校'
    },
    major: {
      required: true,
      trigger: ['blur', 'input'],
      message: '请填写所学专业'
    },
    allDay: {
      type: 'number',
      required: true,
      trigger: ['blur', 'change'],
      message: '请选择预约时间'
    },
    morningAppTime: {
      required: addEditForm.value.allDay === 0 && addEditForm.value.afternoonAppTimeStart==null && addEditForm.value.afternoonAppTimeEnd==null,
      trigger: ['blur', 'change'],
      asyncValidator: (_rule: FormItemRule, _value: string) => {
        return new Promise<void>((resolve: any, reject: any) => {
          if (addEditForm.value.allDay === 0 && addEditForm.value.morningAppTimeStart == null && addEditForm.value.morningAppTimeEnd == null && addEditForm.value.afternoonAppTimeStart == null && addEditForm.value.afternoonAppTimeEnd == null){
            reject(Error('请选择上午或下午时间段'))
          }else if (addEditForm.value.allDay === 0 && addEditForm.value.morningAppTimeStart && addEditForm.value.morningAppTimeEnd == null || addEditForm.value.allDay === 0 && addEditForm.value.morningAppTimeStart == null && addEditForm.value.morningAppTimeEnd){
            reject(Error('请选择上午或下午时间段'))
          }else {
            resolve();
          }
        })
      }
    },
    afternoonAppTime: {
      required: addEditForm.value.allDay === 0 && addEditForm.value.morningAppTimeStart==null && addEditForm.value.morningAppTimeEnd==null,
      trigger: ['blur', 'change'],
      //message: '请选择下午时间段',
      asyncValidator: (_rule: FormItemRule, _value: string) => {
        return new Promise<void>((resolve: any, reject: any) => {
          if (addEditForm.value.allDay === 0 && addEditForm.value.morningAppTimeStart == null && addEditForm.value.morningAppTimeEnd == null && addEditForm.value.afternoonAppTimeStart == null && addEditForm.value.afternoonAppTimeEnd == null){
            reject(Error('请选择上午或下午时间段'))
          }else if (addEditForm.value.allDay === 0 && addEditForm.value.afternoonAppTimeStart && addEditForm.value.afternoonAppTimeEnd == null || addEditForm.value.allDay === 0 && addEditForm.value.afternoonAppTimeStart==null && addEditForm.value.afternoonAppTimeEnd){
            reject(Error('请正确选择下午时间段'))
          }else {
            resolve();
          }
        })
      }
    },
    tCourse:{
      type: 'array',
      required: true,
      trigger: ['blur', 'change'],
      message: '请选择教授科目'
    },
    cPrice:{
      type: 'number',
      required: true,
      trigger: ['blur', 'input'],
      message: '请填写课时价目'
    }
  }
})
const morningAppTimeStartValue = (_value: number | null, formattedValue: string | null) => {
  addEditForm.value.morningAppTimeStartString = formattedValue;
  addEditForm.value.morningAppTime=`${addEditForm.value.morningAppTimeStartString}-${addEditForm.value.morningAppTimeEndString}`;
}
const morningAppTimeEndValue = (_value: number | null, formattedValue: string | null) => {
  addEditForm.value.morningAppTimeEndString = formattedValue;
  addEditForm.value.morningAppTime=`${addEditForm.value.morningAppTimeStartString}-${addEditForm.value.morningAppTimeEndString}`;
}
const afternoonAppTimeStartValue = (_value: number | null, formattedValue: string | null) => {
  addEditForm.value.afternoonAppTimeStartString = formattedValue;
  addEditForm.value.afternoonAppTime=`${addEditForm.value.afternoonAppTimeStartString}-${addEditForm.value.afternoonAppTimeEndString}`;
}
const afternoonAppTimeEndValue = (_value: number | null, formattedValue: string | null) => {
  addEditForm.value.afternoonAppTimeEndString = formattedValue;
  addEditForm.value.afternoonAppTime=`${addEditForm.value.afternoonAppTimeStartString}-${addEditForm.value.afternoonAppTimeEndString}`;
}


//监听出生日
watch(() => addEditForm.value.birthday,
    (date) => {
      birthdayDate.value = date != null ? new Date(date).getTime() : null;
    }
);
//切换查询提交
const handelSelectSearchOption = (value: number | string | null | undefined, field: string) => {
  search_param.value[field] = value;
  handleSubmitSearch();
}
//选择出生日
const selectedBirthday = (value: number | null) => {
  addEditForm.value.birthday = value ? DateFns.ttConversion(value) : null;
}
//选择省份获取地区数据
const getCityOption = (value: number | null, type: number) => {
  if (value) {
    const city: CascaderOption | any = reginData.value.find(item => item.value === value);
    const cityOp = city.children.map((item: any): CascaderOption => ({
      label: item.label,
      value: item.value
    }));
    if (type === 0) {
      cityOptions.value = cityOp;
      addEditForm.value.city = null;
      addEditForm.value.county = null;
      countyOptions.value = [];
    } else {
      addEditForm.value.wCity = null;
      addEditForm.value.wCounty = null;
      wCityOptions.value = cityOp;
      wCountyOptions.value = [];
    }
  } else {
    if (type === 0) {
      addEditForm.value.city = null;
      addEditForm.value.county = null;
      cityOptions.value = [];
      countyOptions.value = [];
    } else {
      addEditForm.value.wCity = null;
      addEditForm.value.wCounty = null;
      wCityOptions.value = [];
      wCountyOptions.value = [];
    }
  }
}
const getCountyOption = (value: number | null, type: number) => {
  if (value) {
    const county = findChildrenByValue(reginData.value, value);
    if (type === 0) {
      addEditForm.value.county = null;
      countyOptions.value = county;
    } else {
      addEditForm.value.wCounty = null;
      wCountyOptions.value = county;
    }
  } else {
    if (type === 0) {
      addEditForm.value.county = null;
      countyOptions.value = [];
    } else {
      addEditForm.value.wCounty = null;
      wCountyOptions.value = [];
    }
  }
}
//选择可预约日期
const changeResDay = (value: number | null) => {
  addEditForm.value.day = value ? DateFns.ttConversion(value) : null;
}
const renderUserLabel = (option: SelectOption) => {
  return h(
      'div',
      {
        style: {
          display: 'flex',
          alignItems: 'center'
        }
      },
      [
        h(NAvatar, {
          src: Config.VIEW_FILE + option.avatar,
          round: true,
          size: 'small'
        }),
        h(
            'div',
            {
              style: {
                marginLeft: '12px',
                padding: '4px 0'
              }
            },
            [
              h('div', null, [option.label as string]),
              h(
                  NText,
                  {depth: 3, tag: 'div'},
                  {
                    default: () => 'ID:' + option.value
                  }
              )
            ]
        )
      ]
  )
}
const renderSingleSelectTag = ({option}) => {
  return h(
      'div',
      {
        style: {
          display: 'flex',
          alignItems: 'center'
        }
      },
      [
        h(NAvatar, {
          src: Config.VIEW_FILE + option.avatar,
          round: true,
          size: 24,
          style: {
            marginRight: '12px'
          }
        }),
        option.label as string
      ]
  )
}


//教授科目处理
const renderLabelSuffix = (option: SelectOption) => {
  return h('div', null, {
    default: () => [
      h('span', null, {default: () => option.name}),
      h('span', null, {default: () => '(' + option.classifyName + '/' + option.gradeName + ')'})
    ]
  })
}
//查询
const handleSubmitSearch = () => {
  data_list.value.searchListData();
}
//重置查询 条件
const handleResetSearch = () => {
  search_param.value.key = null;
  search_param.value.phone = null;
  search_param.value.gender = null;
  search_param.value.auth = null;
  search_param.value.beBusy = null;
  search_param.value.status = null;

}

//修改
const handleEdit = (record: Recordable) => {
  if (record.province) {
    getCityOption(record.province, 0)//籍贯城市
  }
  if (record.city) {
    getCountyOption(record.city, 0)
  }
  if (record.wprovince) {
    getCityOption(record.wprovince, 1)//籍贯城市
  }
  if (record.wcity) {
    getCountyOption(record.wcity, 1)
  }
  addEditForm.value.id = record.id;
  addEditForm.value.name = record.name;
  addEditForm.value.userId = record.userId;
  addEditForm.value.phone = record.phone;
  addEditForm.value.wechat = record.wechat;
  addEditForm.value.idCard = record.idCard;
  addEditForm.value.gender = record.gender;
  addEditForm.value.birthday = record.birthday;
  addEditForm.value.graduate = record.graduate;
  addEditForm.value.education = record.education;
  addEditForm.value.major = record.major;
  addEditForm.value.currentIdentity = record.currentIdentity;
  addEditForm.value.tutor = record.tutor;
  addEditForm.value.province = record.province ? record.province : null;
  addEditForm.value.city = record.city ? record.city : null;
  addEditForm.value.county = record.county ? record.county : null;
  addEditForm.value.address = record.address;
  addEditForm.value.wProvince = record.wprovince ? record.wprovince : null;
  addEditForm.value.wCity = record.wcity ? record.wcity : null;
  addEditForm.value.wCounty = record.wcounty ? record.wcounty : null;
  addEditForm.value.res = record.res;
  addEditForm.value.status = record.status;
  addEditForm.value.beBusy = record.beBusy;
  addEditForm.value.isRec = record.isRec;
  addEditForm.value.auth = record.auth;
  addEditForm.value.evaluation = record.evaluation ? record.evaluation : null;
  addEditForm.value.avatar = record.avatar ? record.avatar : null;
  addEditForm.value.idCardPhoto = record.idCardPhoto ? record.idCardPhoto : null;
  addEditForm.value.jobProve = record.jobProve ? record.jobProve : null;
  addEditForm.value.diploma = record.diploma ? record.diploma : null;
  addEditForm.value.tCourse = record.tcourse.length ? record.tcourse : null;
  addEditForm.value.tArea = record.tarea.length ? record.tarea : null;
  addEditForm.value.honor = record.honor != null && record.honor.length ? record.honor : [];
  addEditForm.value.certificate = record.certificate != null && record.certificate.length ? record.certificate : [];
  if (record.res !== 0) {
    if (record.res === 1) {
      addEditForm.value.day = record.day.split(",").map(Number);
    } else {
      addEditForm.value.day = record.day;
      addEditForm.value.resDay = record.day ? new Date(record.day).getTime() : null;
    }
  }
  addEditForm.value.allDay = record.allDay;
  addEditForm.value.morningAppTime = record.morningAppTime ? record.morningAppTime : null;
  addEditForm.value.afternoonAppTime = record.afternoonAppTime ? record.afternoonAppTime : null;
  addEditForm.value.morningAppTimeStart = record.morningAppTimeStart ? parseInt(record.morningAppTimeStart) : null;
  addEditForm.value.morningAppTimeEnd = record.morningAppTimeEnd ? parseInt(record.morningAppTimeEnd) : null;
  addEditForm.value.afternoonAppTimeStart = record.afternoonAppTimeStart ? parseInt(record.afternoonAppTimeStart) : null;
  addEditForm.value.afternoonAppTimeEnd = record.afternoonAppTimeEnd ? parseInt(record.afternoonAppTimeEnd ): null;
  addEditForm.value.cPrice = record.cprice ? record.cprice: null;
  addEditModel.value = true;
}
//删除
const handleDelete = (record: Recordable) => {
  delRequest('teacher/del', record.id).then((result: ResponseResult) => {
    if (result.status === 0 && result.code === 200) {
      message.success(result.message, {
        duration: 1500,
        onLeave() {
          data_list.value.reload();
        }
      })
    } else {
      message.error(result.message);
    }
  })
}
//提交新增、修改数据
const handelSubmitData = (e: MouseEvent) => {
  e.preventDefault();
  addEditFormRef.value?.validate((errors) => {
    if (!errors) {
      handelSubmitLoading.value = true;
      const url = addEditForm.value.id ? 'teacher/edit' : 'teacher/add';
      postPutRequest(url, addEditForm.value, addEditForm.value.id ? 'PUT' : 'POST').then((result: ResponseResult) => {
        if (result.code === 200) {
          message.success(result.message, {
            duration: 1500,
            onLeave() {
              addEditModel.value = false;
              if (addEditForm.value.id) {
                data_list.value.reload();
              } else {
                data_list.value.searchListData();
              }
            }
          })
        } else {
          message.error(result.message);
          handelSubmitLoading.value = false;
        }
      })
    }
  })
}
//关闭新增、修改教师
const closeAddEditModel = () => {
  addEditForm.value.id = 0;
  addEditForm.value.name = null;
  addEditForm.value.userId = null;
  addEditForm.value.phone = null;
  addEditForm.value.wechat = null;
  addEditForm.value.idCard = null;
  addEditForm.value.gender = 1;
  addEditForm.value.birthday = null;
  addEditForm.value.graduate = null;
  addEditForm.value.education = null;
  addEditForm.value.major = null;
  addEditForm.value.currentIdentity = null;
  addEditForm.value.tutor = null;
  addEditForm.value.province = null;
  addEditForm.value.city = null;
  addEditForm.value.county = null;
  addEditForm.value.address = '';
  addEditForm.value.wProvince = null;
  addEditForm.value.wCity = null;
  addEditForm.value.wCounty = null;
  addEditForm.value.res = 0;
  addEditForm.value.day = null;
  addEditForm.value.resDay = null;
  addEditForm.value.status = 1;
  addEditForm.value.beBusy = 0;
  addEditForm.value.isRec = 0;
  addEditForm.value.auth = 0;
  addEditForm.value.evaluation = null;
  addEditForm.value.avatar = null;
  addEditForm.value.idCardPhoto = null;
  addEditForm.value.jobProve = null;
  addEditForm.value.diploma = null;
  addEditForm.value.tCourse = null;
  addEditForm.value.tArea = null;
  addEditForm.value.honor = [];
  addEditForm.value.certificate = [];
  addEditForm.value.allDay = 0;
  addEditForm.value.morningAppTimeStart = null;
  addEditForm.value.morningAppTimeEnd = null;
  addEditForm.value.afternoonAppTimeStart = null;
  addEditForm.value.afternoonAppTimeEnd = null;
  addEditForm.value.morningAppTime = null;
  addEditForm.value.afternoonAppTime = null;
  addEditForm.value.morningAppTimeStartString=null;
  addEditForm.value.morningAppTimeEndString=null;
  addEditForm.value.afternoonAppTimeStartString=null;
  addEditForm.value.afternoonAppTimeEndString=null;
  addEditForm.value.cPrice = null;
  handelSubmitLoading.value = false;
}
//返回学历名称
const getEdu = (edu: number) => {
  const item: SelectOption | undefined = educationOption.value.find(item => item.value === edu);
  return item && item.label ? item.label : '';
}
//获取区域数据
const getRegin = async () => {
  await getRequest('region/get_tree').then((result: ResponseResult) => {
    const {data} = result;
    reginData.value = convertRegin(data);
  })
}
//处理区域数据
const convertRegin = (data: TreeSelectOption[]) => {
  return data.map((item): CascaderOption => ({
    label: item.label,
    value: item.key,
    ...(item.children && item.children.length > 0 && {children: convertRegin(item.children)}),
  }));
}
const findChildrenByValue = (data: CascaderOption[], value: number): SelectOption[] | undefined => {
  for (const item of data) {
    if (item.value === value) {
      return item.children;
    }
    if (item.children) {
      const found = findChildrenByValue(item.children, value);
      if (found) {
        return found;
      }
    }
  }
  return undefined;
}
//处理授课区域数据
const convertTeachingArea = (data: any[]) => {
  return data.map((item): CascaderOption => ({
    label: item.name,
    value: item.id,
    ...(item.children && item.children.length > 0 && {children: convertTeachingArea(item.children)}),
  }));
}
//获取课程
const getCourse = async () => {
  await getRequest("course/for_vip").then((result: ResponseResult) => {
    const {data} = result;
    courseOptions.value = data;
  })
}
const getUser = async () => {
  await getRequest('user/get_select').then((result: ResponseResult) => {
    const {data} = result;
    usersOptions.value = data;
  })
}
//授课区域
const getTeachingArea=async()=>{
  await getRequest("teacher/get_t_area").then((result: ResponseResult) => {
    const {data} = result;
    TeachingAreaOptions.value = convertTeachingArea(data);
  })
}
onBeforeMount(() => {
  getRegin();
  getUser();
  getCourse();
  getTeachingArea();
})
</script>

<style scoped lang="scss">
.selected-img-list {
  display: grid;
  grid-template-columns: repeat(10, 1fr);
  gap: 10px;
}
</style>